'use client'

import { useState, useEffect, useRef } from 'react'

interface PostInteractionsProps {
  postId: number
}

function initializeCodeBlocks() {
    const copyButtons = document.querySelectorAll('.copy-button')
    copyButtons.forEach(button => {
      if (button instanceof HTMLButtonElement) {
        button.addEventListener('click', async () => {
          const code = decodeURIComponent(button.dataset.code || '')
          const originalCode = code.replace(/<[^>]+>/g, '')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&amp;/g, '&')
            .trim();
          await navigator.clipboard.writeText(originalCode)
          
          button.textContent = '已复制!'
          button.dataset.copied = 'true'
          
          setTimeout(() => {
            button.textContent = '复制'
            button.dataset.copied = 'false'
          }, 2000)
        })
      }
    })
  }

export default function PostInteractions({ postId }: PostInteractionsProps) {
  const [views, setViews] = useState(0)
  const [likes, setLikes] = useState(0)
  const [hasLiked, setHasLiked] = useState(false)
  // 使用useRef存储计时器和AbortController
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const controllerRef = useRef<AbortController | null>(null);
  const viewTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  useEffect(() => {
    // 立即获取浏览量和点赞数，但不记录浏览量
    const fetchData = async () => {
      try {
        // 创建新的AbortController用于取消请求
        controllerRef.current = new AbortController();
        const signal = controllerRef.current.signal;
        
        // 获取浏览量和点赞数
        const response = await fetch(`/api/posts?postId=${postId}&action=all`, { signal });
        if (!response.ok) throw new Error('获取数据失败');
        const data = await response.json();
        
        if (data.views !== undefined) setViews(data.views);
        if (data.likes !== undefined) setLikes(data.likes);
      } catch (error) {
        // 忽略AbortError，这是预期的行为
        if (!(error instanceof DOMException && error.name === 'AbortError')) {
          console.error('获取数据失败:', error);
        }
      }
    };
    
    // 立即执行获取数据
    fetchData();
    
    // 延迟10秒后记录浏览量，确保用户真正在阅读文章
    viewTimerRef.current = setTimeout(() => {
      // 创建新的AbortController用于取消请求
      const viewController = new AbortController();
      const viewSignal = viewController.signal;
      
      // 记录浏览量
      fetch('/api/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ postId }),
        signal: viewSignal
      })
      .then(() => {
        // 浏览量记录成功后，重新获取最新数据
        return fetch(`/api/posts?postId=${postId}&action=views`, { signal: viewSignal });
      })
      .then(res => res.json())
      .then(data => {
        if (data.views !== undefined) setViews(data.views);
      })
      .catch(error => {
        // 忽略AbortError
        if (!(error instanceof DOMException && error.name === 'AbortError')) {
          console.error('记录浏览量失败:', error);
        }
      });
    }, 200); // 10秒延迟
    
    initializeCodeBlocks();
    
    // 清理函数
    return () => {
      // 取消所有进行中的请求
      if (controllerRef.current) {
        controllerRef.current.abort();
        controllerRef.current = null;
      }
      
      // 清除计时器
      if (viewTimerRef.current) {
        clearTimeout(viewTimerRef.current);
        viewTimerRef.current = null;
      }
    };
  }, [postId])

  const handleLike = async () => {
    if (hasLiked) return

    // 创建新的AbortController用于取消请求
    const likeController = new AbortController();
    const signal = likeController.signal;

    try {
      const response = await fetch('/api/posts/like', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ postId }),
        signal
      })
      
      const data = await response.json()
      if (data.likes) {
        setLikes(data.likes)
        setHasLiked(true)
      }
    } catch (error) {
      // 忽略AbortError
      if (!(error instanceof DOMException && error.name === 'AbortError')) {
        console.error('点赞失败:', error)
      }
    }
  }

  return (
    <div className="flex items-center space-x-6 text-sm text-gray-500 dark:text-gray-400">
      <div className="flex items-center">
        <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
        <span>{views} 次阅读</span>
      </div>
      <button
        onClick={handleLike}
        disabled={hasLiked}
        className={`flex items-center ${hasLiked ? 'text-red-500' : 'hover:text-red-500'}`}
      >
        <svg className="w-5 h-5 mr-1" fill={hasLiked ? "currentColor" : "none"} stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
        </svg>
        <span>{likes} 人点赞</span>
      </button>
    </div>
  )
}